package com.cxh.interceptor;

import com.cxh.constant.SsmConstant;
import com.cxh.entity.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//  通过request获取session
        HttpSession session = request.getSession();
        //通过session获取用户信息
        User user = (User) session.getAttribute(SsmConstant.USER_INFO);
        //判断是否为null
        if (user == null) {
            //如果为null重定向到登陆
            response.sendRedirect(request.getContextPath() + "/user/login-ui");
            return false;
        } else {
            //如果用户信息不为null，放行
            return true;
        }


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
